<!-- 企业端-多租户体系-结构树 -->
<template>
  <div class="system">
    <div class="system-left">
      <div class="companyName">
        <el-select
          v-model="companyName"
          filterable
          remote
          clearable
          @change="companyChange"
          :remote-method="remoteCompanyList"
          placeholder="请输入"
        >
          <el-option
            v-for="item in companyList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="organizer">
        <el-tree
          ref="organizerTree"
          v-loading="treeLoading"
          :data="organizerTree"
          node-key="id"
          default-expand-all
          draggable
          highlight-current
          :expand-on-click-node="false"
          :render-content="renderContent"
          @node-drop="handleDragEnd"
          @node-click="getDetailByNodeId"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
          :props="defaultProps"
        />
      </div>
    </div>
    <el-container class="system-right">
      <div class="currentLevelInfo">
        <h4>
          {{ curNode.companyName }}
        </h4>
        <p v-if="parentNode.companyName !== ''">
          上级组织：{{ parentNode.companyName }}
        </p>
      </div>
      <div class="currentLevel-module" v-if="curNode.level === 1">
        <!-- 裁剪上传 -->
        <cropper-upload
          ref="cropperUploadComponent"
          @cropperSubmit="saveOrUpdateStructure"
        ></cropper-upload>
        <div class="sysUpload">
          <h4>体系LOGO图标</h4>
          <div v-if="structureLogo">
            <img
              @click="reUpload"
              style="cursor:pointer;"
              :src="structureLogo"
              alt="logo"
            />
            <div>请上传尺寸为178*34的图片，格式为png、jpg、jpeg</div>
          </div>
          <div v-else>
            <el-upload
              ref="cropperUpload"
              class="upload-demo"
              drag
              :before-upload="beforeAvatarUpload"
              accept=".jpg,.jpeg,.png"
              :show-file-list="false"
              :auto-upload="true"
              action="#"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">上传图片</div>
              <div class="el-upload__tip" slot="tip">
                请上传jpg/jpeg/png文件
              </div>
            </el-upload>
          </div>
        </div>
        <div class="structureName">
          <!-- <h4>体系系统名称</h4> -->
          <!-- <div class="structureNameContent">
            <el-input
              placeholder="请输入体系系统名称"
              v-model="structureName"
            />
            <div class="structureNameMenu">
              <el-button
                type="success"
                size="mini"
                icon="el-icon-check"
                @click="saveOrUpdateStructure('', 'name')"
                circle
              ></el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-close"
                @click="clearStructureName()"
                circle
              ></el-button>
            </div>
          </div> -->
        </div>
      </div>
      <div class="currentLevel-module">
        <div class="currentLevel-module_title">
          <div class="title-left">
            <h4>下级组织</h4>
          </div>
          <div>
            <el-button type="primary" @click="openTheBox"
              >设置批量产线</el-button
            >
            <el-button type="primary" @click="showSubOrgDialog"
              >新增下级组织</el-button
            >
          </div>
        </div>
      </div>
      <el-editable
        class="el-table"
        :data="subOrgList"
        height="200"
        v-loading="tableLoading"
        :columns="subOrgListColumns"
        @selection-change="handleSelectionChange"
      >
        <template slot="default-categoryNames" slot-scope="scope">
          <el-tooltip 
            class="item" 
            effect="dark" 
            placement="top"
            v-for="(v,index) in scope.row.categoryNames" 
            :content="v.categoryChain"
            :key="index">
            <el-tag
              style="float: left; margin: 2px 0 0 3px;"
              size="mini"
              class="categoryInfoList-tag">{{ v.categoryName }}</el-tag>
          </el-tooltip>
        </template>
        <template slot="default-operate" slot-scope="scope">
          <el-button
            size="medium"
            @click.stop="
              delStructureNode(scope.row.id, scope.row.ownerCompanyId)
            "
            type="text"
            >移出</el-button
          >
          <el-button size="medium" @click.stop="toDetail(scope)" type="text"
            >查看</el-button
          >
        </template>
      </el-editable>
      <el-header>
        <el-pagination
          align="right"
          style="margin-top:20px;"
          @size-change="sizeChange"
          :page-sizes="PAGE_NUMBER"
          :page-size="page.size"
          :current-page="page.page"
          @current-change="pageChange"
          :layout="PAGINATION_LAYOUT"
          :total="page.total"
        />
      </el-header>
    </el-container>
    <!-- 新增下级组织 -->
    <add-sub-organizations
      ref="addSubOrganizations"
      @getTree="getStructureTree"
    ></add-sub-organizations>
    <el-dialog
      title="选择产品线"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div class="dialog_content">
        <div class="left">
          <span class="keyword">关键字：</span>
          <el-input
            placeholder="请输入"
            v-model="filterText" />
        </div>
        <div class="button">
        </div>
      </div>
      <div class="treeStructure">
        <el-tree
          class="filter-tree"
          :data="dataList"
          show-checkbox
          node-key="id"
          ref="tree"
          @node-click="handleNodeClick"
          @check-change="handleCheckChange"
          v-loading="productLoading"
          default-expand-all
          :filter-node-method="filterNode"
          :props="defaultPropsSecond">
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary" 
          @click="getAddNode"
          :disabled="getTreeNodeList.length !== 0 === false"
          >确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ElEditable from '@components/el-editable/door/index.vue'
import cropperUpload from '@components/cropperUpload/index.vue'
import {PAGINATION_LAYOUT, PAGE_NUMBER} from '@const/common'
import addSubOrganizations from '@/moduleComponents/structure/addSubOrganizations/index.vue'
import {
  AcOverallStructureFindAcOverallStructureTree,
  AcOverallStructureGetChannelCompanyId,
  AcOverallStructureGetStructureChilds,
  AcOverallStructureFindTreeCompanyName,
  AcOverallStructureEditStructureTree, // 移动体系树
  AcOverallStructureInfoGetByFactoryCompanyId, // 查询体系
  AcOverallStructureInfoSaveOrUpdate, // 保存/更新体系
  AcOverallStructureDel,
  dealerBindProdLineIds
} from '@const/api_authCenter.js'
import {
  getCompanyProdCategoryTypeTreeJustFirstLevel,
} from '@const/prdutCentApi'
import {subOrgListColumns} from './const.js'
import {isNull, hasIn, cloneDeep} from 'lodash'
export default {
  name: 'system',
  components: {ElEditable, cropperUpload, addSubOrganizations},
  data() {
    return {
      dataList: [],
      getTreeNodeList: [],
      defaultPropsSecond: {
        children: 'children',
        label: 'companyProdCategoryName'
      },
      filterText: '',
      dialogVisible: false,
      productLoading: false,
      organizerTree: [], // 组织结构树的数据
      treeLoading: false, // 树的Loading
      subOrgList: [],
      subOrgListColumns,
      tableLoading: false,
      multipleSelection: [],
      companyName: '',
      companyList: [],
      structureName: '',
      defaultProps: {
        children: 'childNode',
        label: 'label'
      },
      structureLogo: '',
      curNode: {},
      parentNode: {},
      parentNodeDrag: {},
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      page: {
        size: 20,
        page: 1,
        total: 0
      },
      companyChangeId: ''
    }
  },
  watch: {
    // 监听关键字搜索
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getStructureTree()
    this.getStructureByFactoryCompanyId()
  },
  methods: {
    //打开产品线的弹框
    openTheBox() {
      if(this.multipleSelection.length > 0) {
        this.dialogVisible = true
        this.getTreeListData()
      }else{
        this.$message.error('请选择企业')
      }
    },
    // 获取树结构数据
    getTreeListData () {
      this.productLoading = true
      this.$axios.get(getCompanyProdCategoryTypeTreeJustFirstLevel)
      .then(res => {
        this.dataList = res.data.payload ? res.data.payload : []
        this.productLoading = false
      })
    },
    // 过滤筛选
    filterNode(value, data) {
      if (!value) return true; 
      return data.companyProdCategoryName.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      const index = this.getTreeNodeList.findIndex(d => d.companyProdCategoryId === data.companyProdCategoryId);
      if(index > -1) {
        this.$refs.tree.setChecked(data,false)
      }else{
        this.$refs.tree.setChecked(data,true)
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      if(checked) {
        this.getTreeNodeList.push(data)
      }else{
        const index = this.getTreeNodeList.findIndex(d => d.companyProdCategoryId === data.companyProdCategoryId);
        this.getTreeNodeList.splice(index, 1)
      }
    },
    //点击弹框确认按钮
    getAddNode() { 
      let params = {
        ids: this.multipleSelection,
        companyProdCategoryIds: this.getTreeNodeList.map(item => {
          return item.companyProdCategoryId
        })
      }
      this.$axios.$post(dealerBindProdLineIds, params)
      .then(res => {
        if(res.code === '0') {
          this.$message({
            type: 'success',
            message: '选择产品线成功!',
          });
          this.dialogVisible = false
          this.getDetailByNodeId(this.curNode)
        }
      })
    },
    // 拖拽时查找上级组织的名称
    searchDragParentOrganization(pid) {
      const getId = arr => {
        arr.forEach(item => {
          if (item.id === pid) {
            this.parentNodeDrag = cloneDeep(item)
          }
          if (item.childNode && item.childNode.length) {
            getId(item.childNode)
          }
        })
      }
      getId(this.organizerTree, pid)
    },
    // 可拖拽的树
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      if (dropType === 'before') {
        this.searchDragParentOrganization(dropNode.data.pid)
        let obj = {
          ancestorId: this.parentNodeDrag.ancestorId,
          companyId: draggingNode.data.companyId,
          id: draggingNode.data.id,
          level: this.parentNodeDrag.level + 1,
          ownerCompanyId: this.parentNodeDrag.ownerCompanyId,
          pid: this.parentNodeDrag.id,
          sort: dropNode.data.sort - 1
        }
        this.upDownNode(obj)
      } else if (dropType === 'after') {
        this.searchDragParentOrganization(dropNode.data.pid)
        let obj = {
          ancestorId: this.parentNodeDrag.ancestorId,
          companyId: draggingNode.data.companyId,
          id: draggingNode.data.id,
          level: this.parentNodeDrag.level + 1,
          ownerCompanyId: this.parentNodeDrag.ownerCompanyId,
          pid: this.parentNodeDrag.id,
          sort: dropNode.data.sort
        }
        this.upDownNode(obj)
      } else {
        let obj = {
          ancestorId: dropNode.data.ancestorId,
          companyId: draggingNode.data.companyId,
          id: draggingNode.data.id,
          level: dropNode.data.level + 1,
          ownerCompanyId: dropNode.data.ownerCompanyId,
          pid: dropNode.data.id,
          sort: 1
        }
        this.upDownNode(obj)
      }
    },
    // 上下移动节点
    upDownNode(dataObj) {
      this.treeLoading = true
      this.$axios({
        method: 'POST',
        url: AcOverallStructureEditStructureTree,
        data: dataObj
      })
        .then(res => {
          this.$message({message: '移动成功', type: 'success'})
          this.getStructureTree(this.companyChangeId)
        })
        .finally(() => {
          this.getStructureTree()
          this.treeLoading = false
        })
    },
    // 拖拽时判定目标节点能否被放置
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.data.pid !== '0') {
        return true
      } else {
        return false
      }
    },
    // 拖拽目标位置是否允许放置
    allowDrag(draggingNode, dropNode, type) {
      return true
    },
    // 新增组织弹框
    showSubOrgDialog() {
      this.$refs.addSubOrganizations.showDialog(this.curNode)
    },
    // 可删除的树
    renderContent(h, {node, data, store}) {
      if (data.level === 1) {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
            <span>
              <span>{node.label}</span>
            </span>
          </span>
        )
      } else {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
            <span>
              <span>{node.label}</span>
            </span>
            <span>
              <div
                class="el-icon-error"
                style="font-size: 12px;margin-left:5px;"
                type="text"
                on-click={() => this.deleteNode(node, data)}
              />
            </span>
          </span>
        )
      }
    },
    deleteNode(node, data) {
      this.delStructureNode(data.id, data.ownerCompanyId)
    },
    // 点击查找上级组织的名称
    searchParentOrganization(pid) {
      if (pid === '0') {
        this.parentNode.companyName = ''
        return false
      }
      const getId = arr => {
        arr.forEach(item => {
          if (item.id === pid) {
            this.parentNode = cloneDeep(item)
          }
          if (item.childNode && item.childNode.length) {
            getId(item.childNode)
          }
        })
      }
      getId(this.organizerTree, pid)
    },
    // 点击获取下级节点
    getDetailByNodeId(node) {
      this.searchParentOrganization(node.pid) // 找上级组织
      this.curNode = node // 当前节点的数据
      let storeId = this.$store.state.companyId
      let subId = ''
      if (node.childNode && node.childNode.length === 1) {
        subId = node.childNode[0].id
      }
      this.$axios({
        url: AcOverallStructureGetStructureChilds,
        method: 'post',
        data: {
          pid: node.id,
          id: subId,
          page: this.page.page,
          size: this.page.size
        }
      })
        .then(res => {
          if (res.data.code === '0') {
            let data = hasIn(res, ['data', 'data', 'content'])
              ? res.data.data.content
              : []
            this.subOrgList = data
            this.page.total = res.data.data ? res.data.data.totalElements : 0
          }
        })
        .finally(() => {})
    },
    // 到客商关系详情
    toDetail(scope) {
      this.$axios({
        url: AcOverallStructureGetChannelCompanyId,
        method: 'POST',
        data: {
          companyId: scope.row.companyId,
          creatUserId: this.$store.state.userId
        }
      })
        .then(res => {
          if (res.data.code === '0') {
            if (res.data.payload.id === null) {
              this.$message.error('未建立渠道商关系')
            } else {
              location.href =
                this.$PATH_CONST.BASICDATA_CHANNELBUSINESSMANAGEMENT_READ +
                '?id=' +
                res.data.payload.id
            }
          }
        })
        .finally(() => {})
    },
    handleSelectionChange(data) {
      this.multipleSelection = data
      this.multipleSelection = this.multipleSelection.map(item => {
        return item.id
      })
    },
    beforeAvatarUpload(file) {
      this.$refs.cropperUploadComponent.showDialog()
      this.$refs.cropperUploadComponent.beforeAvatarUpload(file)
    },
    // 远程搜索公司list
    remoteCompanyList(companyName) {
      this.$axios({
        url: AcOverallStructureFindTreeCompanyName,
        method: 'post',
        data: {
          companyName: companyName,
          ownerCompanyId: this.$store.state.companyId
        }
      })
        .then(res => {
          let data = hasIn(res, ['data', 'payload']) ? res.data.payload : []
          this.companyList = []
          this.companyList = data.map(item => {
            return {
              label: item.companyName,
              value: item.companyId
            }
          })
        })
        .finally(() => {})
    },
    resetOrgTree(list) {
      const getId = arr => {
        arr.forEach(item => {
          let conunt = item.treeCount > 0 ? `(${item.treeCount}家)` : ''
          item.label = item.companyName + conunt
          item.value = item.companyId
          if (item.childNode && item.childNode.length) {
            getId(item.childNode)
          }
        })
      }
      getId(list)
      return list
    },
    companyChange(id) {
      this.companyChangeId = id
      this.getStructureTree(id)
    },
    // 结构树
    getStructureTree(id = '') {
      this.$axios({
        url: AcOverallStructureFindAcOverallStructureTree,
        method: 'post',
        data: {
          ownerCompanyId: this.$store.state.companyId,
          companyId: id
        }
      })
        .then(res => {
          let data = hasIn(res, ['data', 'payload']) ? res.data.payload : []
          if (data.length > 0) {
            this.getDetailByNodeId(data[0]) // 下级组织
            this.organizerTree = this.resetOrgTree(data) // 体系树
            this.$nextTick(() => {
              this.$refs.organizerTree.setCurrentKey(data[0].id) // 高亮
            })
          }
        })
        .finally(() => {})
    },
    // 查询体系
    getStructureByFactoryCompanyId() {
      this.$axios({
        url: `${AcOverallStructureInfoGetByFactoryCompanyId}?factoryCompanyId=${this.$store.state.companyId}`,
        method: 'get'
      })
        .then(res => {
          if (res.data.code === '0') {
            let data = hasIn(res, ['data', 'payload']) ? res.data.payload : []
            this.structureLogo = data.structureLogo
            this.structureName = data.structureName
          }
        })
        .finally(() => {})
    },
    clearStructureName() {
      this.structureName = ''
    },
    // 保存体系
    saveOrUpdateStructure(res, type) {
      let params = {}
      params.factoryCompanyId = this.$store.state.companyId
      if (type === 'img') {
        params.structureLogo = res.data.payload
      } else {
        if (this.structureName === '') {
          this.$message.error('请填写体系系统名称')
          return false
        }
        params.structureName = this.structureName
      }
      this.$axios({
        url: `${AcOverallStructureInfoSaveOrUpdate}?factoryCompanyId=${this.$store.state.companyId}`,
        method: 'post',
        data: params
      })
        .then(res => {
          if (res.data.code === '0') {
            this.getStructureByFactoryCompanyId()
            this.$message.success('操作成功')
          }
        })
        .finally(() => {})
    },
    // 删除体系树节点
    delStructureNode(id, ownerCompanyId) {
      const h = this.$createElement
      this.$confirm('确认提示', {
        title: '确认提示',
        message: h('div', null, [
          h('b', null, '是否确定移出对应的记录？ '),
          h(
            'p',
            null,
            '是否确定移出该企业?移出后，该企业将无法在体系内进行操作。'
          )
        ]),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios({
            url: AcOverallStructureDel,
            method: 'post',
            data: {
              id: id,
              ownerCompanyId: ownerCompanyId
            }
          })
            .then(res => {
              if (res.data.code === '0') {
                this.getStructureTree()
                this.$message.success('删除成功')
              }
            })
            .catch(err => {})
            .finally(() => {})
        })
        .catch(() => {})
    },
    reUpload() {
      document.getElementsByClassName('el-upload')[0].click()
    },
    sizeChange(val) {
      this.page.size = val
      this.getDetailByNodeId(this.curNode)
    },
    pageChange(val) {
      this.page.page = val
      this.getDetailByNodeId(this.curNode)
    }
  }
}
</script>
<style lang="less" type="text/less">
.upload-demo {
  .el-upload {
    width: 60%;
    .el-upload-dragger {
      width: 100%;
      height: 150px;
    }
  }
}
.el-tree-node {
  white-space: nowrap;
  outline: none;
  width: 350px;
  overflow: auto;
}
</style>
<style lang="less" scoped type="text/less">
.system {
  display: flex;

  .orgName {
    display: inline-block;
    min-width: 200px;
  }

  .lastOrg {
    padding: 30px 0;
    text-align: center;
  }

  .menu {
    background-color: rgba(73, 192, 175, 0.1);
    border-color: rgba(73, 192, 175, 0.2);
    color: #49c0af;
  }

  .system-left {
    min-width: 220px;
    min-height: 600px;
    overflow: auto;
    padding: 20px 10px;
    box-sizing: border-box;
    border: 1px solid #e4e4e4;

    .companyName {
      margin-bottom: 10px;
      .el-select {
        width: 100%;
      }
    }

    .system-left-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .font-tip {
      font-size: 12px;
      margin-bottom: 10px;
      color: #dddfe1;
    }
  }

  .el-autocomplete {
    width: 211px;
  }
  // 重置文本框宽度
  .dialog-box {
    .el-textarea {
      width: 218px;
    }
  }
  .system-right {
    margin-left: 10px;
    flex: 1;
    // display: flex;
    // flex-direction: column;
    min-height: 600px;
    padding: 20px 10px;
    box-sizing: border-box;
    border: 1px solid #e4e4e4;
    overflow: scroll;
    .currentLevelInfo {
      margin-bottom: 20px;
      &-title {
        display: flex;
        justify-content: space-between;
        &_left {
          h4 {
            font-size: 20px;
          }
        }
      }
      &_summary {
        color: #606266;
        
      }
    }
    .currentLevel-module {
      // margin: 20px 0;

      .sysUpload {
        > div {
          text-align: center;
          margin: 15px 0;
          img {
            background: #2371c5;
            padding: 10px;
          }
        }
      }
      .structureName {
        .structureNameContent {
          text-align: center;
          width: 60%;
          margin: 0 auto;
          position: relative;
          .structureNameMenu {
            position: absolute;
            right: 15px;
            bottom: 3px;
          }
        }
      }

      &_title {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
      }
      &_content {
        .lowerLevelBox {
          border: 1px solid #ededed;
          &-item {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #ededed;
            padding: 10px 15px;
            &:last-child {
              border-bottom: none;
            }
          }
          .arrow {
            border: none;
            margin-right: 20px;
          }
        }
      }
    }
  }
  .dialog_content{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    .left{
      .keyword{
        width: 70px;
      }
      .el-input {
        width: 250px;
        height: 40px;
      }
      .el-input__icon {
        line-height: 34px;
        height: 34px;
      }
      .el-input__inner {
        height: 34px;
      }
    }
  }
  .treeStructure{
    height: 300px;
    overflow: scroll;
  }
  .cell ,
  .el-tooltip{
    display: flex;
  }
}
</style>
